package com.top145;

public class Solution8 {
    public int myAtoi(String s) {
        if (s.length() == 0) return 0;
        s = s.trim();
        char[] chars = s.toCharArray();
        int index = 0;
        int sign = 1;
        int res = 0;
        if (chars[0] == '-') {
            sign = -1;
            index++;
        } else if (chars[0] == '+') index++;
        while (index < chars.length) {
            if (chars[index] < '0' || chars[index] > '9') break;
            int tmp = chars[index++] - '0' + res * 10;
            if (tmp / 10 != res) return sign == -1 ? Integer.MIN_VALUE : Integer.MAX_VALUE;
            res = tmp;
        }
        return sign * res;
    }
}
